package com.tiantian.novel.resolver.impl;

import com.tiantian.novel.model.ChapterInfo;
import com.tiantian.novel.model.NovelSummary;
import com.tiantian.novel.resolver.NovelResolver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

/**
 * 解析txt类小说
 *
 * @author wangkai
 * @since 2020/12/18.
 */
public class TxtNovelResolver implements NovelResolver {
    private static final Logger log = LoggerFactory.getLogger(TxtNovelResolver.class);
    /**
     * 章节开始分割线----------
     */
    private static final String SPLIT_LINE = "^\\--+$";

    @Override
    public NovelSummary resolveNovelSummary(String url) throws Exception {
        File txt = new File(url);
        if (!txt.exists()) {
            throw new Exception("txt file not exists，【" + url + "】");
        }
        NovelSummary info = new NovelSummary();
        info.setChapters(resolveChaptersFromTxt(txt, SPLIT_LINE));
        return info;
    }

    @Override
    public ChapterInfo resovleChapter(String url) throws Exception {
        throw new Exception("Do not support this method.");
    }

    @Override
    public byte[] getImage(String logo) {
        return null;
    }

    /**
     * 从txt中解析出章节
     *
     * @param file
     * @param splitLine
     *
     * @return
     * @throws Exception
     */
    private static List<ChapterInfo> resolveChaptersFromTxt(File file, String splitLine) throws Exception {
        List<ChapterInfo> chapters = new ArrayList<>();
        // 计算总行数
        int totalLines = getLines(file);
        BufferedReader reader = new BufferedReader(new FileReader(file));
        String line;
        int chapterIndex = 1;
        Pattern splitPattern = Pattern.compile(splitLine);
        ChapterInfo chapter = null;
        StringBuilder content = new StringBuilder();
        for (int i = 0; i < totalLines; i++) {
            if (chapter == null || chapter.isFinished()) {
                // 新章节开始
                chapter = new ChapterInfo(chapterIndex++);
                content = new StringBuilder();
                chapters.add(chapter);
            }
            line = reader.readLine().trim();
            // 空白行
            if (line.isEmpty() || line.startsWith("一秒记住")) {
                continue;
            }
            // 找到章节分割符"-----------"
            if (splitPattern.matcher(line).find()) {
                if (StringUtils.hasText(chapter.getTitle())) {
                    // 章节结束
                    chapter.setContent(content.toString());
                }
                continue;
            }
            if (StringUtils.isEmpty(chapter.getTitle())) {
                chapter.setTitle(line);
            } else {
                content.append(line);
            }
        }
        reader.close();
        return chapters;
    }

    /**
     * 获取总行数
     *
     * @param file
     *
     * @return
     * @throws IOException
     */
    private static int getLines(File file) throws IOException {
        int rowCount = 0;
        BufferedReader reader = new BufferedReader(new FileReader(file));
        while ((reader.readLine()) != null) {
            rowCount++;
        }
        reader.close();
        return rowCount;
    }
}
